<?php

/**
 * Add body classes if certain regions have content.
 */
function goldengroup_preprocess_html(&$variables) {
  //if(in_array('page-login',$variables['classes_array']))
  //$variables['classes_array'][] = 'page-user';

  if (!empty($variables['page']['featured'])) {
    $variables['classes_array'][] = 'featured';
  }

  if (!empty($variables['page']['triptych_first']) || !empty($variables['page']['triptych_middle']) || !empty($variables['page']['triptych_last'])) {
    $variables['classes_array'][] = 'triptych';
  }

  if (!empty($variables['page']['footer_firstcolumn']) || !empty($variables['page']['footer_secondcolumn']) || !empty($variables['page']['footer_thirdcolumn']) || !empty($variables['page']['footer_fourthcolumn'])) {
    $variables['classes_array'][] = 'footer-columns';
  }

  // Add conditional stylesheets for IE
  drupal_add_css(path_to_theme() . '/css/ie.css', array('group' => CSS_THEME, 'browsers' => array('IE' => 'lte IE 7', '!IE' => FALSE), 'preprocess' => FALSE));
  drupal_add_css(path_to_theme() . '/css/ie6.css', array('group' => CSS_THEME, 'browsers' => array('IE' => 'IE 6', '!IE' => FALSE), 'preprocess' => FALSE));
}

/**
 * Override or insert variables into the page template for HTML output.
 */
function goldengroup_process_html(&$variables) {
  // Hook into color.module.
  if (module_exists('color')) {
    _color_html_alter($variables);
  }
  //Begin  remove system css (by ntt)
  //foreach ($variables['css'] as $key => $val) {
  //   if (preg_match('/^(sites\/all\/)?modules\/(system|node|comment|user|overlay|forum|toolbar|feedback|search|locale|date|field)\/.*/', $key) || preg_match('/jquery\.ui\.theme.css/i',$key)) {
  //       unset($variables['css'][$key]);
  //   }
  //}
  //unset($variables['page_top']); //Remove toolbar
  //$variables['styles'] = drupal_get_css($variables['css']);
}

/**
 * Override or insert variables into the page template.
 */
function goldengroup_process_page(&$variables) {
  // Hook into color.module.
  if (module_exists('color')) {
    _color_page_alter($variables);
  }
  // Always print the site name and slogan, but if they are toggled off, we'll
  // just hide them visually.
  $variables['hide_site_name'] = theme_get_setting('toggle_name') ? FALSE : TRUE;
  $variables['hide_site_slogan'] = theme_get_setting('toggle_slogan') ? FALSE : TRUE;
  if ($variables['hide_site_name']) {
    // If toggle_name is FALSE, the site_name will be empty, so we rebuild it.
    $variables['site_name'] = filter_xss_admin(variable_get('site_name', 'Drupal'));
  }
  if ($variables['hide_site_slogan']) {
    // If toggle_site_slogan is FALSE, the site_slogan will be empty, so we rebuild it.
    $variables['site_slogan'] = filter_xss_admin(variable_get('site_slogan', ''));
  }
  // Since the title and the shortcut link are both block level elements,
  // positioning them next to each other is much simpler with a wrapper div.
  if (!empty($variables['title_suffix']['add_or_remove_shortcut']) && $variables['title']) {
    // Add a wrapper div using the title_prefix and title_suffix render elements.
    $variables['title_prefix']['shortcut_wrapper'] = array(
      '#markup' => '<div class="shortcut-wrapper clearfix">',
      '#weight' => 100,
    );
    $variables['title_suffix']['shortcut_wrapper'] = array(
      '#markup' => '</div>',
      '#weight' => - 99,
    );
    // Make sure the shortcut link is the first item in title_suffix.
    $variables['title_suffix']['add_or_remove_shortcut']['#weight'] = -100;
  }
}

/**
 * Implements hook_preprocess_maintenance_page().
 */
function goldengroup_preprocess_maintenance_page(&$variables) {
  if (!$variables['db_is_active']) {
    unset($variables['site_name']);
  }
  drupal_add_css(drupal_get_path('theme', 'bartik') . '/css/maintenance-page.css');
}

/**
 * Override or insert variables into the maintenance page template.
 */
function goldengroup_process_maintenance_page(&$variables) {
  // Always print the site name and slogan, but if they are toggled off, we'll
  // just hide them visually.
  $variables['hide_site_name'] = theme_get_setting('toggle_name') ? FALSE : TRUE;
  $variables['hide_site_slogan'] = theme_get_setting('toggle_slogan') ? FALSE : TRUE;
  if ($variables['hide_site_name']) {
    // If toggle_name is FALSE, the site_name will be empty, so we rebuild it.
    $variables['site_name'] = filter_xss_admin(variable_get('site_name', 'Drupal'));
  }
  if ($variables['hide_site_slogan']) {
    // If toggle_site_slogan is FALSE, the site_slogan will be empty, so we rebuild it.
    $variables['site_slogan'] = filter_xss_admin(variable_get('site_slogan', ''));
  }
}

/**
 * Override or insert variables into the node template.
 */
function goldengroup_preprocess_node(&$variables) {
  if ($variables['view_mode'] == 'full' && node_is_page($variables['node'])) {
    $variables['classes_array'][] = 'node-full';
  }
}

/**
 * Override or insert variables into the block template.
 */
function goldengroup_preprocess_block(&$variables) {
  // In the header region visually hide block titles.
  if ($variables['block']->region == 'header') {
    $variables['title_attributes_array']['class'][] = 'element-invisible';
  }
}

/**
 * Implements theme_field__field_type().
 */
function goldengroup_field__taxonomy_term_reference($variables) {
  $output = '';

  // Render the label, if it's not hidden.
  if (!$variables['label_hidden']) {
    $output .= '<h3 class="field-label">' . $variables['label'] . ': </h3>';
  }

  // Render the items.
  $output .= ($variables['element']['#label_display'] == 'inline') ? '<ul class="links inline">' : '<ul class="links">';
  foreach ($variables['items'] as $delta => $item) {
    $output .= '<li class="taxonomy-term-reference-' . $delta . '"' . $variables['item_attributes'][$delta] . '>' . drupal_render($item) . '</li>';
  }
  $output .= '</ul>';

  // Render the top-level DIV.
  $output = '<div class="' . $variables['classes'] . (!in_array('clearfix', $variables['classes_array']) ? ' clearfix' : '') . '">' . $output . '</div>';

  return $output;
}

/**
 * Implements of hook_pager
 */
function goldengroup_pager($variables) {
  $tags = $variables['tags'];
  $element = $variables['element'];
  $parameters = $variables['parameters'];
  $quantity = $variables['quantity'];
  global $pager_page_array, $pager_total;

  // Calculate various markers within this pager piece:
  // Middle is used to "center" pages around the current page.
  $pager_middle = ceil($quantity / 2);
  // current is the page we are currently paged to
  $pager_current = $pager_page_array[$element] + 1;
  // first is the first page listed by this pager piece (re quantity)
  $pager_first = $pager_current - $pager_middle + 1;
  // last is the last page listed by this pager piece (re quantity)
  $pager_last = $pager_current + $quantity - $pager_middle;
  // max is the maximum page number
  $pager_max = $pager_total[$element];
  // End of marker calculations.
  // Prepare for generation loop.
  $i = $pager_first;
  if ($pager_last > $pager_max) {
    // Adjust "center" if at end of query.
    $i = $i + ($pager_max - $pager_last);
    $pager_last = $pager_max;
  }
  if ($i <= 0) {
    // Adjust "center" if at start of query.
    $pager_last = $pager_last + (1 - $i);
    $i = 1;
  }
  // End of generation loop preparation.   
  $li_previous = theme('pager_previous', array('text' => (isset($tags[1]) ? $tags[1] : '<< Previous'), 'element' => $element, 'interval' => 1, 'parameters' => $parameters));
  $li_next = theme('pager_next', array('text' => (isset($tags[3]) ? $tags[3] : t('>> Next')), 'element' => $element, 'interval' => 1, 'parameters' => $parameters));

  if ($pager_total[$element] > 1) {
    if ($li_previous) {
      if (preg_match('/href="(.*)"/i', $li_previous, $matches)) {
        if (isset($matches[1]))
          $li_previous = str_replace($matches[1], $matches[1] . '?page=0', $li_previous);
      }
      $items[] = array(
        'class' => 'btn-pre',
        'data' => $li_previous,
      );
    }
    // End generation.
    if ($li_next) {
      $items[] = array(
        'class' => 'btn-next',
        'data' => $li_next,
      );
    }

    $page_new = theme('item_list_pager', array('items' => $items, 'attributes' => array('class' => array('paging'))));
    return $page_new;
  }
}

/**
 * Implements of hook_preprocess_page
 */
function goldengroup_preprocess_page(&$vars) {
  if (preg_match('/node\/(\d+)\/submission\/(\d+)\/edit.*/i', $_GET['q'])) {
    $vars['theme_hook_suggestion'] = 'page__webform';
  } else if (preg_match('/node\/44/i', $_GET['q'])) {
    $vars['theme_hook_suggestion'] = 'page__contact';
  } else if (preg_match('/node\/(\d+)\/submission\/(\d+)\/edit.*/i', $_GET['q'])) {
    $vars['theme_hook_suggestion'] = 'page__webform';
  } else if (preg_match('/recruitment/i', $_GET['q'])) {
    $vars['theme_hook_suggestion'] = 'page__recruitment__list';
  } else if (isset($vars['node'])) {
    $vars['theme_hook_suggestion'] = 'page__' . $vars['node']->type;
  }
}

/**
 * Implement of hook_theme
 */
function goldengroup_theme(&$existing, $type, $theme, $path) {
  $hooks['user_login_block'] = array(
    'template' => 'templates/user-login-block',
    'render element' => 'form',
  );
  $hooks['user_register_form'] = array(
    'template' => 'templates/user-register-form',
    'render element' => 'form',
  );
  $hooks['user_profile_form'] = array(
    'template' => 'templates/user-profile-form',
    'render element' => 'form',
  );
  $hooks['tpl_captcha'] = array(
    'template' => 'templates/tpl_captcha',
    'render element' => 'element',
  );
  $hooks['item_list_pager'] = array(
    'variables' => array('items' => array(), 'title' => NULL, 'type' => 'ul', 'attributes' => array()),
  );
  return $hooks;
}

/**
 * Implements of hook preprocess for user_login_block theme
 */
function goldengroup_preprocess_user_login_block(&$vars) {
  $vars['name'] = render($vars['form']['name']);
  $vars['pass'] = render($vars['form']['pass']);
  $vars['submit'] = render($vars['form']['actions']['submit']);
  $vars['rendered'] = drupal_render_children($vars['form']);
}

/**
 * Implements of hook preprocess for user_register_form theme
 */
function goldengroup_preprocess_user_register_form(&$vars) {
  $vars['mail'] = render($vars['form']['account']['mail']);
  $vars['pass'] = render($vars['form']['account']['pass']);
  $vars['captcha'] = render($vars['form']['captcha']);
  $vars['submit'] = render($vars['form']['actions']['submit']);
  $vars['rendered'] = drupal_render_children($vars['form']);
}

/**
 * Implements of hook preprocess for user_profile_form theme
 */
function goldengroup_preprocess_user_profile_form(&$vars) {
  $patterns = array('/<div.*>/', '/<\/div>/');
  $patterns_birthday = array('/<label.*>/', '/<fieldset.*>/', '/<\/fieldset>/', '/<div.*(field-birthday-add-more-wrapper|month|day|year)">/', '/<\/div>/');
  $replacements = array('');
  $vars['field_full_name'] = render($vars['form']['field_full_name']);
  $vars['field_birthday'] = render($vars['form']['field_birthday']);
  $vars['field_birthday'] = preg_replace($patterns_birthday, $replacements, $vars['field_birthday']);
  $vars['field_place_of_birth'] = render($vars['form']['field_place_of_birth']);
  $vars['field_sex'] = render($vars['form']['field_sex']);
  $vars['field_marital_status'] = render($vars['form']['field_marital_status']);
  $vars['picture'] = render($vars['form']['picture']);
  $vars['field_address'] = render($vars['form']['field_address']);
  $vars['field_province'] = render($vars['form']['field_province']);
  $vars['field_home_phone'] = render($vars['form']['field_home_phone']);
  $vars['field_office_phone'] = render($vars['form']['field_office_phone']);
  $vars['field_cell_phone'] = render($vars['form']['field_cell_phone']);
  $vars['mail'] = render($vars['form']['account']['mail']);
  $vars['current_pass'] = render($vars['form']['account']['current_pass']);
  $vars['current_pass'] = preg_replace($patterns, $replacements, $vars['current_pass']);
  $vars['current_pass_required_values'] = render($vars['form']['account']['current_pass_required_values']);
  $vars['pass'] = render($vars['form']['account']['pass']);
  $vars['pass'] = preg_replace($patterns, $replacements, $vars['pass']);
  $vars['field_upload_cv'] = render($vars['form']['field_upload_cv']);
  $vars['timezone'] = render($vars['form']['timezone']);
  $vars['form_id'] = render($vars['form']['#form_id']);
  $vars['action'] = render($vars['form']['#action']);
  $vars['submit'] = render($vars['form']['actions']['submit']);
  $vars['rendered'] = drupal_render_children($vars['form']);
}

/**
 * Remove password strength
 */
function goldengroup_element_info_alter(&$types) {
  if (isset($types['password_confirm']['#process']) && (($position = array_search('user_form_process_password_confirm', $types['password_confirm']['#process'])) !== FALSE)) {
    unset($types['password_confirm']['#process'][$position]);
  }
  if (isset($types['password_confirm'])) {
    $types['password_confirm']['#process'][] = 'custom_password_confirm';
  }
}

/**
 * Alter confirm password type
 */
function custom_password_confirm($element) {
  if ($element['#array_parents'][0] == 'account') {
    $element['pass1']['#theme_wrappers'] = array('custom_form_element');
    $element['pass1']['#prefix'] = '<li>';
    $element['pass1']['#suffix'] = '</li>';
    $element['pass2']['#theme_wrappers'] = array('custom_form_element');
    $element['pass2']['#prefix'] = '<li>';
    $element['pass2']['#suffix'] = '<div class="description">' . t('Provide a password for the new account in both fields.') . '</div></li>';
  }
  return $element;
}

function goldengroup_captcha($variables) {
  $element = $variables['element'];
  if (!empty($element['#description']) && isset($element['captcha_widgets'])) {
    $element['captcha_widgets']['captcha_response']['#theme_wrappers'] = array('custom_form_element');
    return theme('tpl_captcha', array('element' => $element));
  } else {
    return '<div class="captcha">' . $element['#children'] . '</div>';
  }
}

//function goldengroup_date_combo($variables) {
//	$element = $variables['element'];
//	$element['value']['month']['#theme_wrappers'] = array('custom_form_element');
//	$element['value']['month']['#title'] = '';
//
//	$element['value']['day']['#theme_wrappers'] = array('custom_form_element');
//	$element['value']['day']['#title'] = '';
//	$element['value']['year']['#theme_wrappers'] = array('custom_form_element');
//	$element['value']['year']['#title'] = '';
//  return theme('tpl_date_combo', array('element' => $element));
//	$output = theme('form_element_label', $element);
//	print '<pre>';
//	print_r(render($element['value']['month']));
//	print '</pre>';
//	die;
//}

function goldengroup_webform_view_messages($variables) {
  global $user;

  $node = $variables['node'];
  $teaser = $variables['teaser'];
  $page = $variables['page'];
  $submission_count = $variables['submission_count'];
  $user_limit_exceeded = $variables['user_limit_exceeded'];
  $total_limit_exceeded = $variables['total_limit_exceeded'];
  $allowed_roles = $variables['allowed_roles'];
  $closed = $variables['closed'];
  $cached = $variables['cached'];

  $type = 'status';

  if ($closed) {
    $message = t('Submissions for this form are closed.');
  }
  // If open and not allowed to submit the form, give an explanation.
  elseif (array_search(TRUE, $allowed_roles) === FALSE && $user->uid != 1) {
    if (empty($allowed_roles)) {
      // No roles are allowed to submit the form.
      $message = t('Submissions for this form are closed.');
    } elseif (isset($allowed_roles[2])) {
      // The "authenticated user" role is allowed to submit and the user is currently logged-out.
      $login = url('user/login', array('query' => drupal_get_destination()));
      $register = url('user/register', array('query' => drupal_get_destination()));
      if (variable_get('user_register', 1) == 0) {
        $message = t('You must <a href="!login">login</a> to view this form.', array('!login' => $login));
      } else {
        $message = t('You must <a href="!login">login</a> or <a href="!register">register</a> to view this form.', array('!login' => $login, '!register' => $register));
      }
    } else {
      // The user must be some other role to submit.
      $message = t('You do not have permission to view this form.');
    }
  }

  // If the user has exceeded the limit of submissions, explain the limit.
  elseif ($user_limit_exceeded && !$cached) {
    if ($node->webform['submit_interval'] == -1 && $node->webform['submit_limit'] > 1) {
      $message = t('You have submitted this form the maximum number of times (@count).', array('@count' => $node->webform['submit_limit']));
    } elseif ($node->webform['submit_interval'] == -1 && $node->webform['submit_limit'] == 1) {
      $message = t('You have already submitted this form.');
    } else {
      $message = t('You may not submit another entry at this time.');
    }
    $type = 'error';
  } elseif ($total_limit_exceeded && !$cached) {
    if ($node->webform['total_submit_interval'] == -1 && $node->webform['total_submit_limit'] > 1) {
      $message = t('This form has received the maximum number of entries.');
    } else {
      $message = t('You may not submit another entry at this time.');
    }
  }

  // If the user has submitted before, give them a link to their submissions.
  if ($submission_count > 0 && $node->webform['submit_notice'] == 1 && !$cached) {
    if (empty($message)) {
      $message = t('You have already submitted this form.');
    } else {
      $message .= '';
    }
  }

  if ($page && isset($message)) {
    drupal_set_message($message, $type, FALSE);
  }
}

function goldengroup_item_list_pager($variables) {
  $items = $variables['items'];
  $title = $variables['title'];
  $type = $variables['type'];
  $attributes = $variables['attributes'];

  // Only output the list container and title, if there are any list items.
  // Check to see whether the block title exists before adding a header.
  // Empty headers are not semantic and present accessibility challenges.
  $output = '<div class="item-list">';
  if (isset($title) && $title !== '') {
    $output .= '<h3>' . $title . '</h3>';
  }

  if (!empty($items)) {
    $output .= "<$type" . drupal_attributes($attributes) . '>';
    $num_items = count($items);
    $i = 0;
    foreach ($items as $item) {
      $attributes = array();
      $children = array();
      $data = '';
      $i++;
      if (is_array($item)) {
        foreach ($item as $key => $value) {
          if ($key == 'data') {
            $data = $value;
          } elseif ($key == 'children') {
            $children = $value;
          } else {
            $attributes[$key] = $value;
          }
        }
      } else {
        $data = $item;
      }
      if (count($children) > 0) {
        // Render nested list.
        $data .= theme_item_list(array('items' => $children, 'title' => NULL, 'type' => $type, 'attributes' => $attributes));
      }

      $output .= '<li' . drupal_attributes($attributes) . '>' . $data . "</li>\n";
    }
    $output .= "</$type>";
  }
  $output .= '</div>';
  return $output;
}
